package com.cole.gx095.controller;

import com.cole.gx095.Repository.*;
import com.cole.gx095.domain.PurBillData;
import com.cole.gx095.domain.PurBillTableData;
import com.cole.gx095.domain.PurQuery;
import com.cole.gx095.service.PurQueryService;
import com.cole.gx095.controller.utils.CommonRep;
import com.cole.gx095.controller.utils.RedisUtil;
import com.cole.gx095.controller.utils.TimeUtils;
import com.cole.gx095.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/purchase")
@CrossOrigin
@Transactional
public class purchaseController {
    @Autowired
    PurchasecontractRepository purchasecontractRepository;
    @Autowired
    AttachRepository attachRepository;
    @Autowired
    PurQueryService purQueryService;

    @Autowired
    PurchasebillRepository purchasebillRepository;
    @Autowired
    PurBillgoodsRepository purBillgoodsRepository;
    @Autowired
    StockgoodsRepository stockgoodsRepository;


    @GetMapping("/List")
    CommonRep List(Integer currentPage,Integer pageSize){
        Page<Purchasecontract> page1 = purchasecontractRepository.findAll(PageRequest.of(currentPage - 1, pageSize));
        Long sumAmount = purchasecontractRepository.sumAmount();
        return CommonRep.ok()
                .data("page",page1)
                .data("purContractList",page1.getContent())
                .data("sumPurMoney",sumAmount);
    }
    @GetMapping("/getById/{id}")
    CommonRep getById(@PathVariable Integer id){
        Purchasecontract byId = purchasecontractRepository.getById(id);
        return CommonRep.ok()
                .data("purContact",byId);
    }

    /**
     * 获取采购合同所对应的发票数据
     * @param id
     * @return
     */
    @GetMapping("/getBillById/{id}")
    CommonRep getBillById(@PathVariable Integer id){
        Purchasecontract byId = purchasecontractRepository.getById(id);
        System.out.println("byId.getContractNum() = " + byId.getContractNum());
        //此处是从billgood表中找 由于新增发票忘记写billgood表 故bug
        List<PurBillgoods> allBycontractNum = purBillgoodsRepository.findAllBycontractNum(byId.getContractNum());
        List<PurBillTableData> purBillTableDataList = new ArrayList<>();
        for (PurBillgoods purBillgoods : allBycontractNum) {
            Purchasebill purchasebill = purchasebillRepository.getById(purBillgoods.getBillId());
            PurBillTableData purBillTableData = new PurBillTableData();
            purBillTableData.setBillNum(purchasebill.getBillNum());
            purBillTableData.setBillDate(purchasebill.getBillDate());
            purBillTableData.setBillAccount(purchasebill.getBillAccount());
            purBillTableData.setAttachCount(purchasebill.getAttachCount());
            purBillTableData.setUpdateCountbill(purchasebill.getUpdateCount());

            purBillTableData.setTypeName(purBillgoods.getTypeName());
            purBillTableData.setGoodsName(purBillgoods.getGoodsName());
            purBillTableData.setModle(purBillgoods.getModle());
            purBillTableData.setGoodsAccount(purBillgoods.getGoodsAccount());
            purBillTableData.setGoodsUnitPrice(purBillgoods.getGoodsUnitPrice());

            purBillTableData.setGoodsSumPrice(purBillgoods.getGoodsSumPrice());
            purBillTableData.setUsedAccount(purBillgoods.getUsedAccount());
            purBillTableData.setBillType(purchasebill.getBillType());
            purBillTableData.setCreateDate(purchasebill.getCreateDate());
            purBillTableData.setCreateAdminTrueName(purchasebill.getCreateAdminTrueName());
            purBillTableData.setPurBillgoodsId(purBillgoods.getId());
            purBillTableData.setPurchasebillId(purchasebill.getId());
            purBillTableDataList.add(purBillTableData);
        }
        purBillTableDataList.forEach(System.out::println);
        return CommonRep.ok().data("BillTableData",purBillTableDataList);
    }

    /**
     * 复杂查询
     * @param currentPage
     * @param pageSize
     * @param purQuery
     * @return
     */
    @PostMapping("/queryBy")
    CommonRep getById( Integer currentPage,
                       Integer pageSize,
                       PurQuery purQuery){
        System.out.println("purQuery = " + purQuery);

        Page<Purchasecontract> allBy = purQueryService.findAllBy(purQuery, currentPage, pageSize);
        Double sumPurMoney = 0.0;
        for (Purchasecontract purchasecontract1 : allBy) {
            sumPurMoney += purchasecontract1.getContractAmount();
        }
        return CommonRep.ok()
                .data("page",allBy)
                .data("purContractList",allBy.getContent())
                .data("sumPurMoney",sumPurMoney);
    }

    /**
     * 添加采购合同
     * @param purchasecontract
     * @param files
     * @return
     */
    @PostMapping("/add")
    CommonRep add(Purchasecontract purchasecontract,
                  MultipartFile[] files){
        Integer attachCount = 0;
        if(files == null){
            return CommonRep.warn("请传入文件");
        }
//        String staticPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
        System.out.println("staticPath = " + TimeUtils.staticPath);
        if(purchasecontractRepository.findoneBycontractNum(purchasecontract.getContractNum()) != null){
            return CommonRep.warn("请输入唯一编号");
        }
        purchasecontract.setBillAmount(0.0);//发票总金额
        purchasecontract.setBillCount(0);//发票数量
        purchasecontract.setBillStatus(0);//发票状态 未开票
        purchasecontract.setAttachCount(attachCount);//附件数
        purchasecontract.setUpdateCount(0);//更新次数
        purchasecontract.setCreateAdminTrueName(RedisUtil.mget("LoginName"));//创建者
        Purchasecontract savecontract = purchasecontractRepository.save(purchasecontract);

        for (MultipartFile file : files) {
            File file1 = new File(TimeUtils.staticPath+File.separator+"doc"+File.separator+ TimeUtils.getfileTime()+file.getOriginalFilename());
            try {
                file.transferTo(file1);
                System.out.println("file1.getPath() = " + file1.getPath());
                Attach attach = new Attach();
                attach.setAssociationId(savecontract.getId());//关联Id
                attach.setName(file.getOriginalFilename());
                attach.setType(0);//附件类型 0采购合同
                attach.setUrl(file1.getPath());//此处为绝对路径
                attachRepository.save(attach);
                attachCount++;
            } catch (IOException e) {
                e.printStackTrace();
                return CommonRep.warn("存入失败");
            }
        }
        savecontract.setAttachCount(attachCount);
        purchasecontractRepository.save(savecontract);
        return CommonRep.ok();
    }

    /**
     * 采购发票新增
     * 表Purchasebill新增
     * 表Purchasebillgood新增 在addbill1
     * 表purchasecontract补充发票数量
     * @param files
     * @param purBillTableData
     * contractNum
     * billNum
     * billDate
     * billType
     * @return
     */
    @PostMapping("/addBill")
    CommonRep addBill(MultipartFile[] files,
                      PurBillTableData purBillTableData,
                      String contractNum){
        Integer attachCount = 0;
        if(files == null){
            return CommonRep.warn("请上传文件");
        }
//        String staticPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
        System.out.println("staticPath = " + TimeUtils.staticPath);

        Purchasecontract purchasecontract = purchasecontractRepository.findoneBycontractNum(contractNum);
        if(purchasebillRepository.findoneBybillNum(purBillTableData.getBillNum())!=null){
            return CommonRep.warn("请输入唯一编号");
        }
        Purchasebill purchasebill = new Purchasebill();
        purchasebill.setContractId(purchasecontract.getId());
        purchasebill.setContractNum(purchasecontract.getContractNum());
        purchasebill.setBillNum(purBillTableData.getBillNum());
        purchasebill.setBillDate(purBillTableData.getBillDate());
        purchasebill.setBillType(purBillTableData.getBillType());
        purchasebill.setAttachCount(attachCount);
        purchasebill.setBillAccount(0.0);//此处为发票总金额 要补充
        purchasebill.setCreateAdminTrueName(RedisUtil.mget("LoginName"));//创建者
        purchasebill.setUpdateCount(0);
        Purchasebill savebill = purchasebillRepository.save(purchasebill);

        for (MultipartFile file : files) {
            File file1 = new File(TimeUtils.staticPath+File.separator+"doc"+File.separator+ TimeUtils.getfileTime()+file.getOriginalFilename());
            try {
                attachCount++;
                file.transferTo(file1);
                System.out.println("file1.getPath() = " + file1.getPath());
                Attach attach = new Attach();
                attach.setAssociationId(savebill.getId());//关联Id
                attach.setName(file.getOriginalFilename());
                attach.setType(1);//附件类型 1采购发票
                attach.setUrl(file1.getPath());//此处为绝对路径
                attachRepository.save(attach);

            } catch (IOException e) {
                e.printStackTrace();
                return CommonRep.warn("存入失败");
            }
        }
        savebill.setAttachCount(attachCount);
        purchasebillRepository.save(savebill);


        return CommonRep.ok();
    }

    /**
     * 补充addBill
     * 表 Stockgoods 新增
     * 表 PurBillgoods 新增
     * 表 Purchasebill 补充
     *  表purchasecontract补充合同发票总金额 发票状态是否更改
     * @param purBillData
     * billNum;
     * typeName;
     * goodsName;
     * modle;
     * goodsAccount;
     * goodsUnitPrice;
     * goodsSumPrice;
     * @return
     */
    @PostMapping("/addBill1")
    CommonRep addBill1(@RequestBody List<PurBillData> purBillData){
        purBillData.forEach(System.out::println);
        Double BillAccount = 0.0;
        Purchasebill purchasebill = purchasebillRepository.findoneBybillNum(purBillData.get(0).getBillNum());
        Purchasecontract purchasecontract = purchasecontractRepository.getById(purchasebill.getContractId());

        for (PurBillData purBillDatum : purBillData) {
            //计算发票总金额
            BillAccount += purBillDatum.getGoodsSumPrice();
        }
        if(BillAccount + purchasebillRepository.sumAmountBycontractNum(purchasebill.getContractNum()) > purchasecontract.getContractAmount()){
            purchasebillRepository.delete(purchasebill);
            return CommonRep.warn("发票金额大于合同金额");
        }

        for (PurBillData purBillDatum : purBillData) {
            //表 PurBillgoods 新增
            PurBillgoods purBillgoods = new PurBillgoods();
            purBillgoods.setBillId(purchasebill.getId());
            purBillgoods.setContractId(purchasebill.getContractId());
            purBillgoods.setContractNum(purchasebill.getContractNum());
            purBillgoods.setTypeName(purBillDatum.getTypeName());
            purBillgoods.setGoodsName(purBillDatum.getGoodsName());
            purBillgoods.setModle(purBillDatum.getModle());
            purBillgoods.setGoodsAccount(purBillDatum.getGoodsAccount());
            purBillgoods.setGoodsUnitPrice(purBillDatum.getGoodsUnitPrice());
            purBillgoods.setGoodsSumPrice(purBillDatum.getGoodsSumPrice());
            purBillgoods.setStatus(0);//发票状态 先不管 发票明细
            purBillgoods.setUsedAccount(0);//使用量
            purBillgoodsRepository.save(purBillgoods);
            //表 Stockgoods 新增
            Stockgoods stockgoods = new Stockgoods();
            stockgoods.setBillId(purchasebill.getId());
            stockgoods.setBillNum(purchasebill.getBillNum());
            stockgoods.setContractId(purchasebill.getContractId());
            stockgoods.setContractNum(purchasebill.getContractNum());
            stockgoods.setTypeName(purBillDatum.getTypeName());
            stockgoods.setGoodsName(purBillDatum.getGoodsName());
            stockgoods.setModle(purBillDatum.getModle());
            stockgoods.setGoodsAccount(purBillDatum.getGoodsAccount());
            stockgoods.setGoodsUnitPrice(purBillDatum.getGoodsUnitPrice());
            stockgoods.setGoodsSumPrice(purBillDatum.getGoodsSumPrice());
            stockgoods.setCorrelationAccount(0);//关联数量
            stockgoods.setRemainAccount(purBillDatum.getGoodsAccount());//剩余数量
            stockgoods.setRemakes("");
            stockgoodsRepository.save(stockgoods);
        }
        purchasebill.setBillAccount(BillAccount); //补充发票金额
        purchasebillRepository.save(purchasebill);


        purchasecontract.setBillCount(purchasecontract.getBillCount()+1);//发票数量+1
        //补充合同发票总金额 发票状态是否更改
        purchasecontract.setBillAmount(purchasecontract.getBillAmount()+BillAccount);
        if(purchasecontract.getBillAmount() < purchasecontract.getContractAmount())
            purchasecontract.setBillStatus(1);
        else if(purchasecontract.getBillAmount() >= purchasecontract.getContractAmount())
            purchasecontract.setBillStatus(2);
        purchasecontractRepository.save(purchasecontract);

        return CommonRep.ok();
    }

    @PostMapping("/update")
    CommonRep update(@RequestBody Purchasecontract purchasecontract){
        System.out.println("purchasecontract.getId() = " + purchasecontract.getId());
        purchasecontract.setUpdateCount(purchasecontract.getUpdateCount() + 1);
        purchasecontractRepository.save(purchasecontract);
        return CommonRep.ok();
    }
    //billNum  BillDate billType
    //purchasebill 表
    @PostMapping("/updateBill")
    CommonRep updateBill(@RequestBody PurBillTableData purBillTableData){
        System.out.println("purBillTableData = " + purBillTableData);
        Purchasebill purchasebill = purchasebillRepository.getById(purBillTableData.getPurchasebillId());
        purchasebill.setBillNum(purBillTableData.getBillNum());
        purchasebill.setBillType(purBillTableData.getBillType());
        purchasebill.setBillDate(purBillTableData.getBillDate());
        purchasebill.setUpdateCount(purchasebill.getUpdateCount() + 1);
        purchasebillRepository.save(purchasebill);
        return CommonRep.ok();
    }

    //typeName  goodsName modle goodsAccount goodsUnitPrice
    //purBillgoods 表
    @PostMapping("/updateBillDetail")
    CommonRep updateBillDetail(@RequestBody PurBillTableData purBillTableData){
        System.out.println("purBillTableData = " + purBillTableData);
        PurBillgoods purBillgoods = purBillgoodsRepository.getById(purBillTableData.getPurBillgoodsId());
        purBillgoods.setTypeName(purBillTableData.getTypeName());
        purBillgoods.setGoodsName(purBillTableData.getGoodsName());
        purBillgoods.setModle(purBillTableData.getModle());
        purBillgoods.setGoodsAccount(purBillTableData.getGoodsAccount());
        purBillgoods.setGoodsUnitPrice(purBillTableData.getGoodsUnitPrice());

        Double amount = purBillgoods.getGoodsSumPrice();
        purBillgoods.setGoodsSumPrice(purBillTableData.getGoodsAccount() * purBillTableData.getGoodsUnitPrice());
        purBillgoodsRepository.save(purBillgoods);

        Purchasebill purchasebill = purchasebillRepository.findoneBybillNum(purBillTableData.getBillNum());
        purchasebill.setBillAccount(purchasebill.getBillAccount() + purBillTableData.getGoodsAccount() * purBillTableData.getGoodsUnitPrice() - amount);
        purchasebillRepository.save(purchasebill);
        Purchasecontract purchasecontract = purchasecontractRepository.findoneBycontractNum(purchasebill.getContractNum());
        purchasecontract.setBillAmount(purchasecontract.getBillAmount() + purBillTableData.getGoodsAccount() * purBillTableData.getGoodsUnitPrice() - amount);
        if(purBillTableData.getGoodsAccount() * purBillTableData.getGoodsUnitPrice() > amount){
            if(purchasecontract.getBillAmount() < purchasecontract.getContractAmount())
                purchasecontract.setBillStatus(1);
            else if(purchasecontract.getBillAmount() >= purchasecontract.getContractAmount())
                purchasecontract.setBillStatus(2);
            purchasecontractRepository.save(purchasecontract);
        }
        return CommonRep.ok();
    }
}
